package com.tengju.user.infrastructure.listener;

import com.tengju.data.domain.model.alert.AlertEvent;
import com.tengju.data.domain.model.alert.AlertService;
import com.tengju.user.application.archives.StarManageService;
import com.tengju.user.application.club.ClubManageService;
import com.tengju.user.domain.model.user.StarChangeEvent;
import com.tengju.user.domain.shared.JsonUtil;
import com.tengju.user.domain.shared.SpringEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * @author chenhang
 * @Date 2021/1/15
 */
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class StarChangeListener implements ApplicationListener<SpringEvent>,DomainEventListener {

    private final ClubManageService clubManageService;
    private final StarManageService starManageService;
    private final AlertService alertService;

    @Override
    public void onApplicationEvent(SpringEvent springEvent) {
        StarChangeEvent starChangeEvent = checkDomainEvent(springEvent, StarChangeEvent.class);
        if (starChangeEvent == null) {
            return;
        }
        log.info("收到星级变更消息：{}", JsonUtil.toJSONString(starChangeEvent));
        processWithClub(starChangeEvent);
        processWithStarFeature(starChangeEvent);
    }

    private void processWithStarFeature(StarChangeEvent starChangeEvent) {
        try {
            starManageService.updateUserStarFeature(starChangeEvent);
        } catch (Exception e) {
            log.error("星级变更监听失败-星级标签维护" + JsonUtil.toJSONString(starChangeEvent),e);
            AlertEvent alertEvent = new AlertEvent("星级变更监听失败-星级标签维护");
            alertEvent.addItem("内容",JsonUtil.toJSONString(starChangeEvent));
            alertEvent.addItem("异常",e.getMessage());
            alertService.alert(alertEvent);
        }
    }

    private void processWithClub(StarChangeEvent starChangeEvent) {
        try {
            clubManageService.updateStarChange(starChangeEvent);
        } catch (Exception e) {
            log.error("星级变更监听失败-俱乐部关系维护" + JsonUtil.toJSONString(starChangeEvent),e);
            AlertEvent alertEvent = new AlertEvent("星级变更监听失败-俱乐部关系维护");
            alertEvent.addItem("内容",JsonUtil.toJSONString(starChangeEvent));
            alertEvent.addItem("异常",e.getMessage());
            alertService.alert(alertEvent);
        }
    }


}
